package com.guanyong.webapi.controllers.api;

import com.guanyong.model.MerchantLogModel;
import com.guanyong.model.MerchantModel;
import com.guanyong.model.VideoSourceModel;
import com.guanyong.services.MerchantLogService;
import com.guanyong.services.MerchantService;
import com.guanyong.services.VideoSourceService;
import com.guanyong.utils.Comm.ResultCode;
import com.guanyong.utils.Comm.ResultObject;
import com.guanyong.webapi.config.CreateVideoURLUtil;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by Administrator on 2017/9/19 0019.
 */
@RestController
@RequestMapping("/api/verify/")
public class VerifyApi {


//    public static String AccessKey="fc72a728629b410280ae55b24168a78d";
//    public static String SecretKey="3154e4f924594e54bd635cbbe5d32d6f";
    public static String AccessKey="123456";
    public static String SecretKey="654321";
//    String AccessKey = UUID.randomUUID().toString().replace("-", "");
//    String SecretKey = UUID.randomUUID().toString().replace("-", "");

    @Autowired
    VideoSourceService videoSourceService;
    @Autowired
    CreateVideoURLUtil createVideoURLUtil;
    @Autowired
    MerchantLogService merchantLogService;

    @Autowired
    MerchantService merchantService;






    public static void main(String[] args) {





        System.out.println(AccessKey);
        System.out.println(SecretKey);
    }

    @RequestMapping(value = "getvideoURL", method = RequestMethod.GET)
    public ResultObject<String> getvideoURL(HttpServletRequest request,
                                  @RequestParam String objectid,
                                  @RequestParam String datetime,
                                  @RequestParam String key,
                                  @RequestParam String sign,
                                  @RequestParam String verify,
                                  @RequestParam String username,
                                  @RequestParam String userip){
        //获取秘钥对
        ResultObject<MerchantModel> re=merchantService.GetMerchantModelByAk(key);
        MerchantModel merchantModel=re.getResult();
        ResultObject<String> result = new ResultObject<String>();
        if (merchantModel!=null){
            //sha1验证字符串
            String toSignStr = String.format("%s%s%s%s", objectid, datetime, key,merchantModel.getSk());
            //MD5字符串
            String toVerifyStr = String.format("%s%s%s%s%s%s", objectid, datetime, key,sign,username,userip);

            try {
                //生成MD5
                String verifyedStr= VerifyApi.EncoderByMd5(toVerifyStr);
                if (verifyedStr.equals(verify)){
                    //生成sha1
                    String signedStr = VerifyApi.getSha1(toSignStr);
                    if (signedStr.equals(sign)){
                        System.out.println("sign ok");
                        VideoSourceModel videoSourceModel= videoSourceService.GetVideoScorceByObjectIdShow(objectid);
                        String path =createVideoURLUtil.getVideoURL(videoSourceModel.getfSourceurl());
                        result.setResult(path);
                        String serverip=com.guanyong.utils.NetUtils.IPUtil.getIpAddr(request);
                        MerchantLogModel merchantLogModel = new MerchantLogModel();
                        merchantLogModel.setAk(key);
                        merchantLogModel.setIntime(new Date().toString());
                        merchantLogModel.setIp(userip);
                        merchantLogModel.setObjectId(objectid);
                        merchantLogModel.setServerIp(serverip);
                        merchantLogModel.setUrl(path);
                        merchantLogModel.setUserName(username);
                        merchantLogService.addMerchantLog(merchantLogModel);
                    }
                }else {
                    result.setErrorMsg(ResultCode.OperateFail);
                }
            } catch (Exception e) {
                result.setErrorMsg(ResultCode.OperateFail);
                e.printStackTrace();
                return result;
            }
        }else {
            result.setErrorMsg(ResultCode.OperateFail);
        }




        return result;
    }


    public static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException{
        //确定计算方法
        MessageDigest md5=MessageDigest.getInstance("MD5");
        byte[] bs = md5.digest(str.getBytes());
        return Hex.encodeHexString(bs);
//        StringBuilder sb = new StringBuilder(40);
//        for(byte x:bs) {
//            if((x & 0xff)>>4 == 0) {
//                sb.append("0").append(Integer.toHexString(x & 0xff));
//            } else {
//                sb.append(Integer.toHexString(x & 0xff));
//            }
//        }
//        return sb.toString();
    }

    public static String getSha1(String str){
        if (null == str || 0 == str.length()){
            return null;
        }
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));
            byte[] md = mdTemp.digest();
            return Hex.encodeHexString(md);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

}
